package com.yimi.yinhepda.db.helper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.yimi.yinhepda.base.BaseApplication;
import com.yimi.yinhepda.db.dao.BillRouteTableDao;
import com.pda.uce.commom.util.LogUtil;

import java.io.File;

/**
 * 需要实现该抽象类类进行通过实体进行创建表
 *
 * @author 000432
 */
public class DbHelperUC extends OrmLiteSqliteOpenHelper {

    public static final String TAG = DbHelperUC.class.getName();

    /**
     * 数据库版本号
     */
    private static final int TABLE_VERSION = 1;

    /**
     * 数据库文件名称
     */
    public static final String DB_NAME = "BillRoute.db";
    public static final String DB_ZIP_NAME = "RouteDb.zip";
    /**
     * 数据库文件夹
     */
    private static final String DB_FILE_DIR = "database";
    /**
     * 数据库路径
     */
    public static String DB_PATH;

    private static DbHelperUC INSTANCE;

    static {
        File mFile = BaseApplication.getContext().getExternalFilesDir(DB_FILE_DIR);
        if (mFile != null) {
            DB_PATH = mFile.getAbsolutePath() + File.separator;
            if (!mFile.exists()) {
                if (mFile.mkdirs()) {
                    LogUtil.e("初始化database到内存卡成功");
                } else {
                    DB_PATH = "";
                    LogUtil.e("初始化database到机身内存成功");
                }
            }
        }
    }

    public DbHelperUC(Context context) {
        super(context, DB_PATH + DB_NAME, null, TABLE_VERSION);
    }

    /**
     * 数据库Helper 获取实例化
     */
    public static DbHelperUC getInstance(Context context) {
        if (INSTANCE == null) {
            synchronized (DbHelperUC.class) {
                if (INSTANCE == null) {
                    INSTANCE = new DbHelperUC(context);
                }
            }
        }
        return INSTANCE;
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        LogUtil.e("UColdVersion---------->" + oldVersion);
        if (oldVersion >= newVersion) {
            return;
        }
    }

    @Override
    public void close() {
        super.close();
        if (INSTANCE.isOpen()) {
            INSTANCE.close();
        }
        if (INSTANCE != null) {
            INSTANCE = null;
        }
    }

    /**
     * 清除数据
     */
    public static void deleteData() {
        //删除7前天的数据
        new BillRouteTableDao().deleteDataBefore7Day();
    }
}
